const path = require('path')
const fs = require('fs')

const resolve = dir => path.resolve(__dirname, dir)
const isProd = process.env.NODE_ENV === 'production'
const isTestBuild = process.env.BUILD_MODE === 'test'
const entries = JSON.parse(fs.readFileSync(resolve('./build/config.entries.json'), 'utf-8'))
const entry = {}

process.env.VUE_APP_PATH = '/'
if (isTestBuild) process.env.VUE_APP_PATH = '/h5/interview/'
else if (isProd) process.env.VUE_APP_PATH = '/h5/interview/'

const {
  VUE_APP_ENTRY,
  VUE_APP_LIBS,
} = process.env


if (!VUE_APP_LIBS && VUE_APP_ENTRY) {
  const { port } = entries.find(({ value }) => value === VUE_APP_ENTRY)
  process.env.VUE_APP_PORT = port
  Object.assign(entry, {
    name: VUE_APP_ENTRY,
    port,
  })
}

const { VUE_APP_PATH } = process.env

const getPages = () => {
  const res = {}
  if (!VUE_APP_LIBS && VUE_APP_ENTRY) {
    res[entry.name] = {
      entry: `src/pages/${entry.name}/main.js`,
      template: `src/pages/${entry.name}/index.html`,
      filename: 'index.html',
    }
  }
  return res
}

const getOutputDir = () => {
  const res = 'dist'
  if (VUE_APP_LIBS) return `${res}/libs`
  if (VUE_APP_ENTRY) {
    if (VUE_APP_ENTRY === 'master') return res
    return `${res}/micro/${VUE_APP_ENTRY}`
  }
  return res
}

const getPublicPath = () => {
  let res = VUE_APP_PATH
  if (!isProd && !VUE_APP_LIBS && VUE_APP_ENTRY) {
    res = `http://localhost:${entry.port || 8100}${res}`
  }
  if (!isProd || entry.name === 'master') return res
  return `${res}micro/${entry.name}/`
}

module.exports = {
  publicPath: getPublicPath(),
  outputDir: getOutputDir(),
  pages: getPages(),
  productionSourceMap: false,
  parallel: true,
  runtimeCompiler: true,
  filenameHashing: !VUE_APP_LIBS,

  // css: {
  //   loaderOptions: {
  //     sass: {
  //       prependData: ({ resourcePath }) => {
  //         if (resourcePath) return '@import "@libs/global-style/var.scss";'
  //         return ''
  //       },
  //     },

  //     less: {
  //       lessOptions: {
  //         modifyVars: {
  //           hack: 'true; @import "~@/libs/global-style/vant.less";',
  //         },
  //       },
  //     },
  //   },
  // },

  devServer: {
    open: true,
    port: entry.port || 8100,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    historyApiFallback: {
      index: '/index.html',
    },
  },

  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src'),
        '@libs': resolve('src/libs'),
        '@home': resolve('src/pages/home'),
      },
    },
  },

  chainWebpack: (config) => {
    if (VUE_APP_LIBS) {
      const libs = require('./build/config.libs')
      libs.forEach((lib) => {
        config
          .entry(lib)
          .add(`./src/libs/${lib}/index.js`)
          .end()
      })

      config.output
        .filename('[name].min.js')
        .library(['libs', '[name]'])
        .libraryTarget('umd')
        .libraryExport('default')
        .end()

      config.optimization.delete('splitChunks')
    } else if (VUE_APP_ENTRY) {
      config.output
        .library(VUE_APP_ENTRY === 'master' ? 'master' : `${VUE_APP_ENTRY}-[name]`)
        .libraryTarget('umd')
        .jsonpFunction(`webpackJsonp_${VUE_APP_ENTRY}`)
        .end()
    }

    if (isProd) {
      const externals = {
        vue: 'Vue',
        vuex: 'Vuex',
        'vue-router': 'VueRouter',
        vant: 'vant',
        'vant/lib/index.css': 'vant',
        '@libs': 'libs',
      }

      config.externals(externals)
      config.module
        .rule('images')
        .use('url-loader')
        .loader('url-loader')
        .tap(options => Object.assign(options, {
          limit: 10240,
          name: 'img/[name].[hash:8].[ext]',
          publicPath: getPublicPath(),
        }))
        .end()
    }

    if (!VUE_APP_ENTRY) {
      config
        .plugin('copy')
        .use(require('copy-webpack-plugin'), [[
          {
            from: path.resolve(__dirname, './public'),
            to: resolve('./dist'),
          },
          {
            from: path.resolve(__dirname, './node_modules/vant/lib/vant.min.js'),
            to: resolve('./dist/vendor/vant'),
          },
          {
            from: path.resolve(__dirname, './node_modules/vant/lib/index.css'),
            to: resolve('./dist/vendor/vant'),
          },
          {
            from: path.resolve(__dirname, './node_modules/vue/dist/vue.global.prod.js'),
            to: resolve('./dist/vendor/vue.min.js'),
          },
          {
            from: path.resolve(__dirname, './node_modules/vuex/dist/vuex.global.prod.js'),
            to: resolve('./dist/vendor/vuex.min.js'),
          },
          {
            from: path.resolve(__dirname, './node_modules/vue-router/dist/vue-router.global.prod.js'),
            to: resolve('./dist/vendor/vue-router.min.js'),
          },
        ]])
    } else {
      config
        .plugin('copy')
        .use(require('copy-webpack-plugin'), [[
          {
            from: path.resolve(__dirname, './public'),
            ignore: ['*'],
          },
        ]])
    }
  },
}
